# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 09:22:00 2020
策略为三种：
一，直接选保真度最高的
二，如果保真度不比之前的高，就选次优的
三，如果保真度不比之前的高，就选最差的
两个比特各自可以选择不同的动作，但每个比特上，选用的动作都是单方向的。
@author: Waikikilick
"""

import numpy as np
from scipy.linalg import expm
from time import *
import multiprocessing as mp
np.random.seed(1)


action_space = np.array([[1,0,0], #可以选择的动作范围，各列的每项分别代表着 sigma x, y, z 前面的系数。
                       [2,0,0], #每次执行的动作都是单独的绕 x, y, z 轴一定角度的旋转
                       [0,1,0], # x, y 方向的值可以取负，但 z 方向的只能取正值
                       [0,2,0],
                       [0,0,1],
                       [0,0,2],
                       [-1,0,0],
                       [-2,0,0],
                       [0,-1,0],
                       [0,-2,0],
                       [0,0,0]])

s_x = np.mat([[0,1],[1,0]],dtype=complex)
s_y = np.mat([[0,-1j],[1j,0]],dtype=complex)
s_z = np.mat([[1,0],[0,-1]],dtype=complex)
H_c = np.kron((s_x+1j*s_y)/2, (s_x-1j*s_y)/2) + np.kron((s_x-1j*s_y)/2, (s_x+1j*s_y)/2)

init_set_num = 32
target_set_num = init_set_num

qubit_1 = np.mat([[1,0],[0,0]],dtype=complex)
qubit_2 = np.mat([[0,0],[0,1]],dtype=complex)



alpha_num = 8
theta = [np.pi/8,np.pi/4,3*np.pi/8]
theta_1 = theta
theta_2 = theta
theta_3 = theta

alpha = np.linspace(0,np.pi*2,alpha_num,endpoint=False)
alpha_1 = alpha
alpha_2 = alpha
alpha_3 = alpha
alpha_4 = alpha

a_list_complex = np.matrix([[0,0,0,0]],dtype=complex) #第一行用来占位，否则无法和其他行并在一起，在最后要注意去掉这一行
for ii in range(3): #theta_1
    for jj in range(3): #theta_2
        for kk in range(3): #theta_3
            for mm in range(alpha_num): #alpha_1
                for nn in range(alpha_num): #alpha_2
                    for oo in range(alpha_num): #alpha_3
                        for pp in range(alpha_num): #alpha_4
                            
                            a_1_mo = np.cos(theta_1[ii])
                            a_2_mo = np.sin(theta_1[ii])*np.cos(theta_2[jj])
                            a_3_mo = np.sin(theta_1[ii])*np.sin(theta_2[jj])*np.cos(theta_3[kk])
                            a_4_mo = np.sin(theta_1[ii])*np.sin(theta_2[jj])*np.sin(theta_3[kk])
                            
                            a_1_real = a_1_mo*np.cos(alpha_1[mm])
                            a_1_imag = a_1_mo*np.sin(alpha_1[mm])
                            a_2_real = a_2_mo*np.cos(alpha_2[nn])
                            a_2_imag = a_2_mo*np.sin(alpha_2[nn])
                            a_3_real = a_3_mo*np.cos(alpha_3[oo])
                            a_3_imag = a_3_mo*np.sin(alpha_3[oo])
                            a_4_real = a_4_mo*np.cos(alpha_4[pp])
                            a_4_imag = a_4_mo*np.sin(alpha_4[pp])
                            
                            a_1_complex = a_1_real + a_1_imag*1j
                            a_2_complex = a_2_real + a_2_imag*1j
                            a_3_complex = a_3_real + a_3_imag*1j
                            a_4_complex = a_4_real + a_4_imag*1j
                            
                            a_complex = np.matrix([[ a_1_complex, a_2_complex, a_3_complex, a_4_complex]])
                            a_list_complex = np.row_stack((a_list_complex,a_complex))
                            
psi_set = np.array(np.delete(a_list_complex,0,axis=0)) # 删除矩阵的第一行
np.random.shuffle(psi_set) #打乱顺序
init_set = psi_set[:init_set_num]


def target_set():
    target_set = psi_set[init_set_num : init_set_num + target_set_num]
    return target_set

#动作直接选最优的
def step(psi,target_psi,F):
    fid_list = []
    psi_list = []
    
    for action1 in range(len(action_space)): #action1 是第一个比特上采用的动作
        for action2 in range(len(action_space)): #action2 是第二个比特上采用的动作
        
            H_12 = (np.kron(qubit_1,action_space[action1,0]*s_x) + np.kron(qubit_1,action_space[action1,1]*s_y) + np.kron(qubit_1,action_space[action1,2]*s_z)+ np.kron(qubit_2,action_space[action2,0]*s_x) + np.kron(qubit_2,action_space[action2,1]*s_y) + np.kron(qubit_2,action_space[action2,2]*s_z))/2
    
            H = H_12 + H_c
            U = expm(-1j * H * dt) 
            psi_ = U * psi
            fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
            
            psi_list.append(psi_)
            fid_list.append(fid)
    best_action = fid_list.index(max(fid_list))
    best_fid = max(fid_list)
    psi_ = psi_list[best_action]
    # print(best_action)
    return best_action, best_fid, psi_


#动作选最优的，或者最差的
def step1(psi,target_psi,F):
    fid_list = []
    psi_list = []
    
    for action1 in range(len(action_space)): #action1 是第一个比特上采用的动作
        for action2 in range(len(action_space)): #action2 是第二个比特上采用的动作
        
            H_12 = (np.kron(qubit_1,action_space[action1,0]*s_x) + np.kron(qubit_1,action_space[action1,1]*s_y) + np.kron(qubit_1,action_space[action1,2]*s_z)+np.kron(qubit_2,action_space[action2,0]*s_x) + np.kron(qubit_2,action_space[action2,1]*s_y) + np.kron(qubit_2,action_space[action2,2]*s_z))/2
    
            H = H_12 + H_c
            U = expm(-1j * H * dt) 
            psi_ = U * psi
            fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
            
            psi_list.append(psi_)
            fid_list.append(fid)
        
    if F < max(fid_list):
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
    else:
        
        best_action = fid_list.index(min(fid_list))
        best_fid = min(fid_list)
    psi_ = psi_list[best_action]
    return best_action, best_fid, psi_

#动作选最优的，或者次优的
def step2(psi,target_psi,F):
    fid_list = []
    psi_list = []
    for action1 in range(len(action_space)): #action1 是第一个比特上采用的动作
        for action2 in range(len(action_space)): #action2 是第二个比特上采用的动作
        
            H_12 = (np.kron(qubit_1,action_space[action1,0]*s_x) + np.kron(qubit_1,action_space[action1,1]*s_y) + np.kron(qubit_1,action_space[action1,2]*s_z)+np.kron(qubit_2,action_space[action2,0]*s_x) + np.kron(qubit_2,action_space[action2,1]*s_y) + np.kron(qubit_2,action_space[action2,2]*s_z))/2
    
            H = H_12 + H_c
            U = expm(-1j * H * dt) 
            psi_ = U * psi
            fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
            
            psi_list.append(psi_)
            fid_list.append(fid)
        
    if F < max(fid_list):
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
    else:
        del psi_list[fid_list.index(max(fid_list))]
        del fid_list[fid_list.index(max(fid_list))]
        
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
        
        # best_action = fid_list.index(min(fid_list))
        # best_fid = min(fid_list)
    psi_ = psi_list[best_action]
    # print(best_action)
    return best_action, best_fid, psi_
#---------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
def job(target_psi):
    ffid_list = np.zeros((init_set_num ,1))
    target_psi = np.mat(target_psi).T
    for k in range(init_set_num):
        psi1 = np.mat(init_set[k]).T
        psi = psi1
        F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
        fid_max = 0
        fid_max1 = 0
        fid_max2 = 0
        fid_max0 = 0
        step_n = 0
        while True:
            action, F, psi_ = step1(psi,target_psi,F)
            
            fid_max1 = max(F,fid_max1)
            psi = psi_
            step_n += 1
            if fid_max1>0.999 or step_n>step_max:
                break
            
        step_n = 0
        F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
        psi = psi1
        while True:
            action, F, psi_ = step2(psi,target_psi,F)
            fid_max2 = max(F,fid_max2)
            psi = psi_
            step_n += 1
            if fid_max2>0.999 or step_n>step_max:
                break 
            
        fid_max = max(fid_max1,fid_max2)
        if fid_max < 0.999:
            step_n = 0
            F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
            psi = psi1
            while True:
                action, F, psi_ = step(psi,target_psi,F)
                fid_max0 = max(F,fid_max0)
                psi = psi_
                step_n += 1
                if fid_max0>0.999 or step_n>step_max:
                    break 
            fid_max = max(fid_max,fid_max0)  
        ffid_list[k] = fid_max
    return  np.mean(ffid_list)


def multicore():
    pool = mp.Pool()
    F_list = pool.map(job, target_set)
    return F_list

    
if __name__ == '__main__':
    target_set = init_set
    time1 = time()
    for kT in [10]:#:
        for kdt in [3,4,8]:# 3 8
            F_list = []
            T = kT*np.pi
            dt = np.pi/kdt
            step_max = T/dt
        
            F_list = multicore()
            # print(F_list)
            print("kT = ",kT,"kdt = ",kdt,"mean_fid = ",np.mean(F_list))
            # print(np.mean(F_list))
    time2 = time()
    print('time_cost is: ',time2-time1)
    
# kT =  10 kdt =  2 mean_fid =  0.9563342165527313
# kT =  10 kdt =  5 mean_fid =  0.9719666054346767
# kT =  10 kdt =  6 mean_fid =  0.9702838871385591
# kT =  10 kdt =  10 mean_fid =  0.9567220400902572
# kT =  10 kdt =  20 mean_fid =  0.9417133082361093
# kT =  10 kdt =  40 mean_fid =  0.9345555988011582
# kT =  10 kdt =  3 mean_fid =  0.9654781925730606
# kT =  10 kdt =  4 mean_fid =  0.9730852424646352
# kT =  10 kdt =  8 mean_fid =  0.9633110934614078
# kT =  11 kdt =  2 mean_fid =  0.9570656464390042
# kT =  11 kdt =  5 mean_fid =  0.9727956516120927   
# kT =  5 kdt =  2 mean_fid =  0.9439739325964613
# kT =  5 kdt =  3 mean_fid =  0.9558518130188024
# kT =  5 kdt =  4 mean_fid =  0.9642853378839273
# kT =  5 kdt =  5 mean_fid =  0.9625234436822911
# kT =  5 kdt =  8 mean_fid =  0.9530880001165287
# kT =  5 kdt =  10 mean_fid =  0.9479641868611446
# kT =  12 kdt =  2 mean_fid =  0.9588316616837053
# kT =  12 kdt =  3 mean_fid =  0.9674437965048532
# kT =  12 kdt =  4 mean_fid =  0.9748252674758715
# kT =  12 kdt =  5 mean_fid =  0.9738439000250121
# kT =  12 kdt =  8 mean_fid =  0.9656695918117868
# kT =  12 kdt =  10 mean_fid =  0.9587612406719404
# kT =  15 kdt =  2 mean_fid =  0.9612881061103562
# kT =  15 kdt =  3 mean_fid =  0.9697153276648609
# kT =  15 kdt =  4 mean_fid =  0.9766918243319913
# kT =  15 kdt =  5 mean_fid =  0.9759114382633138
# kT =  15 kdt =  8 mean_fid =  0.9679536201754898
# kT =  15 kdt =  10 mean_fid =  0.9609408300774143

